﻿// ------------------------------------------------------------------------
// 版权信息
// 版权归重庆虫儿飞科技有限公司所有。
// 所有权利保留。
// 官方网站：https://netokit.com
// 许可证信息
// Neto.Kit 项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。
// 许可证的完整文本可以在源代码树根目录中的 LICENSE-APACHE 和 LICENSE-MIT 文件中找到。
// 
// 使用条款
// 使用本代码应遵守相关法律法规和许可证的要求。
// 
// 免责声明
// 对于因使用本代码而产生的任何直接、间接、偶然、特殊或后果性损害，我们不承担任何责任。
// 
// 其他重要信息
// Neto.Kit 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。
// 有关 Neto.Kit 项目的其他详细信息，请参阅位于源代码树根目录中的 COPYRIGHT 和 DISCLAIMER 文件。
// 
// 更多信息
// 请访问 https://netokit.com 获取更多关于 Neto.Kit 项目的许可证和版权信息。
// ------------------------------------------------------------------------

using Furion.DynamicApiController;
using Microsoft.Extensions.DependencyInjection;
using Neto.Db.SqlSugar;
using Neto.Db.SqlSugar.Paged;

namespace Neto.Application.Api;

/// <summary>
/// 敏感词管理表
/// </summary>
[Authorize]//jwt授权
[ApiDescriptionSettings("Api", Name = "SysSensitiveWord")]
//[MaApi(controller: "SysSensitiveWord", controllerDescription: "敏感词管理表", PCode = "Api")]
[ApiArea("Api")]
[PgApiController("敏感词管理表服务", MenuPCode = "Sys_Setting")]
[PgApiMenu("敏感词管理", "sys-setting_sensitive-word", MenuPCode = "Sys_Setting", Sort = 10,Icon = "openmoji:prohibited")]
//[Route("Api/[controller]/[action]")]
public class ApiSysSensitiveWordService(ISqlSugarClient db, IServiceProvider _serviceProvider)
: IDynamicApiController
{

    /// <summary>
    /// 新增一条
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [PgApiAction(name: "新增一条")]
    [OperationId(nameof(Insert))]
    public async Task<long> Insert(ApiSysSensitiveWordInput input)
    {
        //验证 父级下 唯一 Key是否存在
        var isexit = await db.Queryable<SysSensitiveWord>().AnyAsync(o => o.Word == input.Word);
        if (isexit)
        {
            throw Oops.Bah("敏感词不能重复");
        }
        var addentity = input.Adapt<SysSensitiveWord>();
        if (await db.InsertRsIdAsync(addentity) == 0)
        {
            throw Oops.Oh("添加失败");

        }

        ReloadWord();
        return addentity.Id;
    }


    /// <summary>
    /// 更新一条
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [PgApiAction(name: "更新一条")]
    [OperationId(nameof(Update))]
    [HttpPut]
    public async Task<bool> Update(ApiSysSensitiveWordInput input)
    {
        ////验证 父级下 唯一 Key是否存在
        var isexit = await db.Queryable<SysSensitiveWord>().AnyAsync(o => o.Word == input.Word && o.Id != input.Id);
        if (isexit)
        {
            throw Oops.Bah("敏感词不能重复");
        }
        var dbentity = await db.Queryable<SysSensitiveWord>().With(SqlWith.Null).FirstAsync(o => o.Id == input.Id.Value);
        input.Adapt(dbentity);
        if (!await db.UpdateAsync(dbentity))
        {
            throw Oops.Oh("更新失败");
        }

        //重载敏感词
        ReloadWord();

        return true;

    }

    /// <summary>
    /// 删除一条
    /// </summary>
    /// <param name="id"></param>
    [PgApiAction(name: "删除一条")]
    [OperationId(nameof(Delete))]
    public async Task<bool> Delete(long id)
    {
        //if (id <= 0) throw Oops.Bah("id不能为0");
        //return  await db.DeleteByIdAsync<SysSensitiveWord>(id);
        await db.FakeDeleteAsync<SysSensitiveWord>($"{id}");

        ReloadWord();

        return true;
    }

    /// <summary>
    /// 批量删除
    /// </summary>
    /// <param name="ids">需要删除的数据，多条以英文逗号隔开</param>
    [PgApiAction(name: "批量删除")]
    [OperationId(nameof(BatchDelete))]
    public async Task<bool> BatchDelete(string ids)
    {
        //return await db.DeleteByIdsAsync<SysSensitiveWord>(ids);
        await db.FakeDeleteAsync<SysSensitiveWord>(ids);

        ReloadWord();

        return true;
    }



    /// <summary>
    /// 重载敏感词
    /// </summary>
    private void ReloadWord()
    {
        //重载敏感词
        using (var scope = _serviceProvider.CreateScope())
        {
            var sensitiveService = scope.ServiceProvider.GetRequiredService<SensitiveWordService>();
            sensitiveService.LoadAllWords();
        }
    }
    /// <summary>
    /// 查询一条
    /// </summary>
    /// <param name="id"></param>
    [PgApiAction(name: "查询一条")]
    [HttpPost]
    [OperationId(nameof(Get))]
    public async Task<ApiSysSensitiveWordOut> Get(long id)
    {
        /* 多表关联的一个写法，当然也可以用导航写法
         var query5 = await db.Queryable<SysSensitiveWord>()
           //.LeftJoin<Custom>   ((o, cus ) => o.CustomId == cus.Id)//多个条件用&&
           //.LeftJoin<OrderDetail> ((o, cus, oritem) => o.Id == oritem.OrderId)
           .Where(o => o.Id == id)  
           .Select((o) => new ApiSysSensitiveWordOut {
                Id = o.Id.SelectAll(), //Id是o任意一个属性
                //CustomName = cus.Name,
            })
           .FirstAsync();
        */

        return await db.GetByIdAsync<SysSensitiveWord, ApiSysSensitiveWordOut>(id);
    }


    /// <summary>
    /// 分页查询
    /// </summary>
    /// <param name="searchQuery"></param>
    /// <returns></returns>
    [PgApiAction(name: "分页查询")]
    [HttpPost]
    [OperationId(nameof(GetList))]
    public async Task<PagedList<ApiSysSensitiveWordOut>> GetList(ApiSysSensitiveWordQuery searchQuery)
    {
        /*
            var queryable = db.Queryable<SysSensitiveWord, OrderItem, Custom>((o, i, c) => new JoinQueryInfos(
                   JoinType.Left, o.Id == i.OrderId, //左连接 左链接 左联 
                   JoinType.Left, o.CustomId == c.Id 
            ));
        */

        var queryable = db.Queryable<SysSensitiveWord>();
        #region 筛选条件
        ////开始日期
        //if (searchQuery.StartDate.HasValue)
        //{
        //    queryable = queryable.Where(o => o.CreationTime >= searchQuery.StartDate.Value);
        //}
        ////结束日期
        //if (searchQuery.EndDate.HasValue)
        //{
        //    queryable = queryable.Where(o => o.CreationTime <=  searchQuery.EndDate.ToDayEndTime());
        //}
        ////关键词
        //if (!string.IsNullOrWhiteSpace(searchQuery.KeyWords))
        //{
        //    var kw = searchQuery.KeyWords?.Trim()?.ToLower() ?? "";
        //    queryable = queryable.Where(o => o.Title.Contains(kw));
        //}
        #endregion

        queryable = queryable.OrderByDescending(o => o.Id);
        var pagelist = await queryable.Select(o => new ApiSysSensitiveWordOut()
        {
            Id = o.Id.SelectAll(),
            #region 自定义
            //IsEnableName =  o.IsEnable?"是":"否"  ,//是否启用 
            //IsDeletedName =  o.IsDeleted?"是":"否"  ,//默认假删除 
            #endregion
        })
        .Mapper(src =>
        {
        })
        .ToPagedListAsync(searchQuery.PageIndex, searchQuery.PageSize);



        //var pagelist= await pageResult.ToPagedListAsync<SysSensitiveWord, ApiSysSensitiveWordOut>(searchQuery.PageIndex, searchQuery.PageSize);

        return pagelist;
    }


    /// <summary>
    /// 设置状态
    /// </summary>
    /// <param name="id"></param>
    /// <param name="state"></param>
    /// <returns></returns>
    [PgApiAction(name: "设置启用状态")]
    [OperationId(nameof(SetIsEnable))]
    public async Task<bool> SetIsEnable(long id, bool state)
    {
        return await db.SetStateByIdAsync<SysSensitiveWord>(id, state, "IsEnable");
    }

    #region 冗余方法
    ///// <summary>
    ///// 查询所有
    ///// </summary>
    ///// <returns></returns>
    //[PgApiAction(name: "查询所有")]
    //[OperationId(nameof(GetAll))]
    //public async Task<List<ApiSysSensitiveWordOut>> GetAll()
    //{
    //    return await db.GetListAsync<SysSensitiveWord, ApiSysSensitiveWordOut>();
    //}

    ///// <summary>
    ///// 获取下拉选项
    ///// </summary>
    ///// <returns></returns>
    //[PgApiAction(name: "获取下拉选项")]
    //[HttpPost]
    //[OperationId(nameof(GetSelectItems))]
    //public async Task<List<NKeyValue<long, string>>> GetSelectItems()
    //{
    //    var keyValues = await db.Queryable<SysSensitiveWord>()
    //        .Select(o => new NKeyValue<long, string>() { Key = o.Id, Value = o.Name })
    //        .ToListAsync();
    //    return keyValues;
    //}


    #endregion

}